package com.example.ccj.b.c.form;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.example.ccj.R;
import com.example.ccj.b.c.custom.MImageView;
import com.example.ccj.b.c.custom.SelectPictureMode;
import com.example.ccj.b.c.custom.TransverseLoadImageControl;
import com.example.ccj.b.c.dialog.QRCodeDialog;
import com.example.ccj.b.c.ui.BoMaKaiGuanControl;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.TimeUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.text.TextInputType;
import com.github.gzuliyujiang.wheelpicker.DatimePicker;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.entity.DatimeEntity;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.luck.picture.lib.entity.LocalMedia;
import java.util.ArrayList;

/**
 * 表单字段
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/6/26 23:28
 */
public class InPutData extends LinearLayout {

    public InPutData(Context context) {
        super(context);
        initView();
    }

    public InPutData(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public InPutData(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    public InPutData(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }


    TextInputLayout inputLayout;
    TextInputEditText inputEditText;
    TransverseLoadImageControl imgRec;
    MImageView rightImg;
    FieldConfig fieldConfig;
    BoMaKaiGuanControl boMaKaiGuanControl;
    TextView stat;

    private void initView(){
        LayoutInflater.from(getContext()).inflate(R.layout.custom_in_put_data, this);
        inputLayout = findViewById(R.id.custom_in_put_data_input_layout);
        boMaKaiGuanControl = findViewById(R.id.custom_in_put_data_input_bo_ma);
        inputEditText = findViewById(R.id.custom_in_put_data_input_edit);
        imgRec = findViewById(R.id.custom_in_put_data_input_img_rec);
        rightImg = findViewById(R.id.custom_in_put_data_input_right_img);
        stat = findViewById(R.id.custom_in_put_data_stat);

        inputEditText.addTextChangedListener(inputTextWatcher);
    }

    private void init(AttributeSet attrs){
        initView();
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs,R.styleable.InPutData);
        if (fieldConfig == null) fieldConfig = new FieldConfig();
        fieldConfig.fieldName = typedArray.getString(R.styleable.InPutData_in_put_field_name);
        fieldConfig.maxLength = typedArray.getInt(R.styleable.InPutData_in_put_max_length,255);
        fieldConfig.textSize = typedArray.getInt(R.styleable.InPutData_in_put_text_size,15);
        fieldConfig.isNoNull = typedArray.getBoolean(R.styleable.InPutData_in_put_is_no_null,false);
        fieldConfig.hintTextColor = typedArray.getColor(R.styleable.InPutData_in_put_hint_text_color, Color.parseColor("#686868"));
        fieldConfig.errorTextColor = typedArray.getColor(R.styleable.InPutData_in_put_error_text_color, Color.parseColor("#F44336"));
        fieldConfig.inputTextColor = typedArray.getColor(R.styleable.InPutData_in_put_error_text_color, Color.parseColor("#000000"));
        typedArray.recycle();
        setUpConfig(fieldConfig);
    }

    TextWatcher inputTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        @Override
        public void afterTextChanged(Editable s) {
            if (fieldConfig.type == MFormField.TEXT || fieldConfig.type == MFormField.NUMBER || fieldConfig.type == MFormField.XIAO_SHU) {
                fieldConfig.setText(s.toString());
                if (fieldConfig.getTextChange() != null) fieldConfig.getTextChange().change(s.toString(),InPutData.this);
            }
            check();
        }
    };

    public boolean check(){
        if (getVisibility() == GONE) return true; // 未显示直接返回true
        if (fieldConfig.type == MFormField.BOOLEAN) return true;
        inputLayout.setErrorEnabled(false);
        if (fieldConfig.isNoNull && StringUtils.isEmpty(fieldConfig.getText())) {
            inputLayout.setError("-不可为空！");
            return false;
        }

        if (fieldConfig.maxLength > -1 && fieldConfig.getText() != null && fieldConfig.getText().length() > fieldConfig.maxLength) {
            inputLayout.setError("最大长度" + fieldConfig.maxLength);
            return false;
        }
        return true;
    }

    public void setInputType(@MFormField.Type int type){
        if (!fieldConfig.isCanModify) return;
        switch (type) {
            case MFormField.TEXT:

                break;

                //数字
            case MFormField.NUMBER:
                if (fieldConfig.maxLength > 0) TextInputType.setEditTextInPutTypeToInt(inputEditText,fieldConfig.maxLength);
                else TextInputType.setEditTextInPutTypeToInt(inputEditText,fieldConfig.maxLength);
                inputEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
                break;

                //小数
            case MFormField.XIAO_SHU:
                if (fieldConfig.maxLength > 0) TextInputType.setEditTextInPutTypeToDouble(inputEditText,fieldConfig.maxLength,2);
                else TextInputType.setEditTextInPutTypeToDouble(inputEditText);
                break;

                //扫码
            case MFormField.SCAN:
                inputEditText.setKeyListener(null);
                rightImg.setVisibility(VISIBLE);
                rightImg.setImageResource(R.mipmap.scan);
                rightImg.setOnClickListener(scanClick);
                break;

                //单选
            case MFormField.DAN_OPTION:
                inputEditText.setKeyListener(null);
                rightImg.setVisibility(VISIBLE);
                rightImg.setImageResource(R.mipmap.right);
                rightImg.setOnClickListener(danOptionClick);
                //初始化当前选项
                if (!StringUtils.isEmpty(fieldConfig.text)) {
                    try {
                        int i = Integer.parseInt(fieldConfig.text.toString());
                        getOptionText(i);
                    } catch (NumberFormatException n) {
                        LogUtils.e("setInputType: 初始化选项文本失败！" + fieldConfig.text);
                    }
                }
                break;
                //多选
            case MFormField.MULTIPLE_OPTION:
                inputEditText.setKeyListener(null);
                rightImg.setVisibility(VISIBLE);
                rightImg.setImageResource(R.mipmap.right);
                rightImg.setOnClickListener(multipleOptionClick);
                break;

            //跳转
            case MFormField.JUMP:
                inputEditText.setKeyListener(null);
                rightImg.setVisibility(VISIBLE);
                rightImg.setImageResource(R.mipmap.right);
                rightImg.setOnClickListener(jumpClick);
                break;

                //图片
            case MFormField.IMG:
                inputLayout.setVisibility(GONE);
                inputEditText.setVisibility(GONE);
                imgRec.setVisibility(VISIBLE);
                imgRec.showTitle(fieldConfig.fieldName,R.mipmap.def_select_img);
                imgRec.setMode(SelectPictureMode.pickMultiplePictureOrCamera);
                imgRec.setCanDelete(true);
                if (fieldConfig.getText() != null) {
                    String[] split = fieldConfig.getText().toString().split(",");
                    for (String s : split) {
                        fieldConfig.localMediaList = new ArrayList<>();
                        LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(s);
                        fieldConfig.localMediaList.add(localMedia);
                        imgRec.setPictureList(fieldConfig.localMediaList);
                    }
                }

                imgRec.setLoadImageControlImageListener(pictureList -> {
                    fieldConfig.localMediaList = pictureList;
                    if (fieldConfig.optionFormatter != null) {
                        //返回图片处理
                        fieldConfig.text = fieldConfig.optionFormatter.result(fieldConfig.dataName,0,pictureList);
                    }
                });
                break;

                //日期
            case MFormField.TIME:
                inputEditText.setKeyListener(null);
                rightImg.setVisibility(VISIBLE);
                rightImg.setImageResource(R.mipmap.time);
                rightImg.setOnClickListener(timeClick);
                break;

                //boolean
            case MFormField.BOOLEAN:
                inputEditText.setKeyListener(null);
                inputEditText.setText("");
                boMaKaiGuanControl.setVisibility(VISIBLE);
                if (fieldConfig.text == null || (!fieldConfig.text.equals("true") && !fieldConfig.text.equals("false"))) {
                    boMaKaiGuanControl.setSelect(false);
                } else {
                    boMaKaiGuanControl.setSelect("true".equalsIgnoreCase(fieldConfig.text.toString()));
                }
                boMaKaiGuanControl.setBoMaOnClickListener(isSelect -> {
                    if (isSelect) {
//                inputEditText.setText("是");
                        fieldConfig.text = "1";
                    } else {
//                inputEditText.setText("否");
                        fieldConfig.text = "0";
                    }
                    if (fieldConfig.getTextChange() != null) fieldConfig.getTextChange().changeBoolean(isSelect,this);
                });
                break;
        }
    }

    /**
     * 单选按钮点击事件
     */
    View.OnClickListener danOptionClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (fieldConfig.option == null || fieldConfig.option.length < 1) {
                LogUtils.d("单项选择-加载表单字段: 选项字段未赋予选项");
                ToastUtils.showShort("该选项未配置");
                return;
            }

            OptionPicker optionPicker = new OptionPicker(ActivityUtils.getTopActivity());
            optionPicker.getWheelView().setFormatter(item -> {
                if (fieldConfig.optionFormatter != null) {
                    String s = fieldConfig.optionFormatter.formatItem(fieldConfig.dataName, item);
                    if (s == null) return item.toString();
                    else return s;
                } else {
                    return item.toString();
                }
            });
            optionPicker.setData(fieldConfig.option);
            optionPicker.setTitle(fieldConfig.fieldName);
            optionPicker.setBodyHeight(200);
            optionPicker.setDefaultPosition(0);
            optionPicker.setOnOptionPickedListener((position, item) -> {
                getOptionText(position);
            });
            optionPicker.show();
        }
    };

    String xianShi;
    /**
     * 设置选项文本
     * 默认显示选择数据的toString()
     * 默认保存文本选择数据的编号
     * @param position 当前选择的编号
     */
    private void getOptionText(int position){
        if (fieldConfig.option == null || fieldConfig.option.length == 0) return;
        Object item = fieldConfig.option[position];
        String result;
        if (fieldConfig.optionFormatter != null) {
            result = fieldConfig.optionFormatter.result(fieldConfig.dataName, position, item);
            if (result == null) result = String.valueOf(position);
            xianShi = fieldConfig.optionFormatter.formatItem(fieldConfig.dataName, item);
            if (xianShi == null)  xianShi = item.toString();
        } else {
            result = item.toString();
            xianShi = item.toString();
        }
        fieldConfig.text = result;
        post(() -> inputEditText.setText(xianShi)) ;
    }

    View.OnClickListener jumpClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (fieldConfig.optionFormatter != null) fieldConfig.optionFormatter.jump(fieldConfig.dataName,InPutData.this);
        }
    };

    View.OnClickListener multipleOptionClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            ToastUtils.showShort("多项选择");
        }
    };

    View.OnClickListener scanClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            ToastUtils.showShort("扫码");
            QRCodeDialog dialog = new QRCodeDialog(v.getContext(), value -> {
                fieldConfig.setText(value);
                inputEditText.setText(value);
            });
            dialog.show();
        }
    };

    View.OnClickListener timeClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            ToastUtils.showShort("日期");
            DatimePicker datimePicker = new DatimePicker(ActivityUtils.getTopActivity());
            datimePicker.setOnDatimePickedListener((year, month, day, hour, minute, second) -> {
                String s = TimeUtils.formatDateTime(year, month, day,hour,minute,second,true);
                fieldConfig.setText(s);
                inputEditText.setText(s);
            });
            datimePicker.getWheelLayout().setDefaultValue(DatimeEntity.now());
            datimePicker.show();
        }
    };

    public void setFieldConfig(FieldConfig fieldConfig) {
        this.fieldConfig = fieldConfig;
        setUpConfig(fieldConfig);
    }

    private void setUpConfig(FieldConfig fieldConfig){
        //是否可修改
        if (fieldConfig.isCanModify()) {
            inputEditText.setTextColor(fieldConfig.inputTextEnabledFalseColor);
        } else {
            inputEditText.setKeyListener(null);
            inputEditText.setTextColor(fieldConfig.inputTextColor);
            rightImg.setVisibility(GONE);
        }
        //原始文本
        if (fieldConfig.type != MFormField.BOOLEAN && !StringUtils.isEmpty(fieldConfig.getText())) post(() -> inputEditText.setText(fieldConfig.getText()));
        //文本大小
        inputEditText.setTextSize(fieldConfig.textSize);
        //文本是否只读
        if (fieldConfig.isOnlySelect()) inputEditText.setKeyListener(null);

        if (fieldConfig.isNoNull) stat.setVisibility(VISIBLE);

        //字段名称
        if (StringUtils.isEmpty(fieldConfig.hint)) inputLayout.setHint(fieldConfig.fieldName);
        else inputLayout.setHint(fieldConfig.hint);
        inputLayout.setHintTextColor(ColorStateList.valueOf(fieldConfig.hintTextColor));
        inputLayout.setErrorEnabled(false);
        post(() -> setInputType(fieldConfig.type));
    }

    public TextInputLayout getInputLayout() {
        return inputLayout;
    }

    public TextInputEditText getInputEditText() {
        return inputEditText;
    }

    public FieldConfig getFieldConfig() {
        return fieldConfig;
    }


}
